//
//  CZUserAccount.swift
//  SinaWeiBo
//
//  Created by 刘幼寒 on 5/18/16.
//  Copyright © 2016 刘幼寒. All rights reserved.
//

import UIKit

//对象归档和解档
//1.对象遵守NScoding协议：知道对象要保存和解档那些属性
//2.调用归档和解档的方法

//用户账号
class CZUserAccount: NSObject,NSCoding
{
    ///用户授权的唯一票据
    var access_token: String?
    ///access_token的生命周期，单位是秒数,基本数据类型不能使用？KVC会找不到
    var expires_in: NSTimeInterval = 0{
        didSet{
            //KVC给expires_in属性赋值完成后，来创建expiresDate
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///过期时间
    var expiresDate: NSDate?
    
    
    
    ///授权用户的UID
    var uid: String?
    //通过字典来创建模型
    init(dict: [String : AnyObject])
    {
        super.init()
        //对象创建好后才能使用对象的方法，内部会调用setValue(value: AnyObject?, forKey: String),每次拿一个key和value调用一次
        setValuesForKeysWithDictionary(dict)
    }
    
//    override func setValue(value: AnyObject?, forKeyPath keyPath: String) {
//        
//        super.setValue(value, forKeyPath: keyPath)
//        CZprint(items: "\(keyPath) : \(value)")
//    }
    override func setValue(value: AnyObject?, forKey key: String)
    {
        super.setValue(value, forKey: key)
//        CZprint(items: "\(key) : \(value)")
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String)
    {
//        CZprint(items: "forUnderfineKey : \(key)")
    }
    
    //打印方法 description属性
    override var description: String {
        get {
            return "asscess_token: \(access_token),expires_in: \(expires_in),uid: \(uid)"
        }
    }
    
    //MARK: - 归档和解档
    ///解档
    required init?(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    }
    
    ///归档
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }

}
